﻿Imports System.Reflection
Imports System.Globalization



Public Class AlertGroupForm
    Implements IAlertGroupClient

    'いろいろテストしながらやってます。
    'コード整理は後でやりますので～

#Region "変数宣言・構造体宣言"

    Structure Alertkind
        Dim kindName As String
        Dim isEnable As Boolean
    End Structure

    Structure SettingsAGF
        Dim settingName As String
        Dim value As Boolean
        Dim alertKindList As List(Of Alertkind)
    End Structure

#Region "グリッドビューのインデックス、設定記憶用変数"
    'インデックスを覚える
    Dim DataGridView_Right_IndexRemember As Integer
    Dim DataGridView_Left_IndexRemember As Integer
    '削除可能かどうか
    Dim CanDelete As Boolean = False
    '名前を一時的に覚えておく
    Dim SettingNameRemember As String
#End Region


#End Region



    Private Sub AlertGroupUI_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        leftDataGridView.AutoGenerateColumns = False
        leftDataGridView.Rows.Add()
        leftDataGridView("SettingName", leftDataGridView.Rows.Count - 1).Value = "既定の設定"
        leftDataGridView("SettingFlag", 0).Value = True
        leftDataGridView("SettingFlag", 0).Value = True
        leftDataGridView("SettingFlag", 0).ReadOnly = True '設定1は変更不可能
        leftDataGridView.DefaultCellStyle.NullValue = "値が設定されていません" 'このメッセージは本来表示されないはず....
    End Sub

#Region "データグリッドビューから設定Listを出力。後でクラスの詳細がわかればいろいろする予定"
    Function OutputSettings() As List(Of SettingsAGF)
        Dim SettingList As New List(Of SettingsAGF)
        Dim rowIndex As Integer = 0
        Dim clmIndex As Integer = 0

        While (rowIndex < leftDataGridView.RowCount)
            clmIndex = 2

            Dim mySettings As New SettingsAGF
            mySettings.value = CBool(leftDataGridView(0, rowIndex).Value)
            mySettings.settingName = leftDataGridView(1, rowIndex).Value.ToString()

            While (clmIndex < leftDataGridView.ColumnCount)
                Dim kind = New Alertkind
                kind.kindName = leftDataGridView.Columns(clmIndex).HeaderText.ToString
                kind.isEnable = CBool(leftDataGridView(clmIndex, rowIndex).Value)
                mySettings.alertKindList.Add(kind)
            End While
            SettingList.Add(mySettings)
            rowIndex += 1
        End While
        Return SettingList
    End Function
#End Region




    'とりあえずMonoのなんとか?
    Private ReadOnly Property IsRunnungOnMono() As Boolean
        Get
            Return Type.GetType("Mono.Runtime") IsNot Nothing
        End Get
    End Property



#Region "OKボタンをおしたときの処理"

    Private Sub Button_OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles okButton.Click

    End Sub
#End Region

#Region "保留中(勉強中)"

    'Denebのアレを参考にする予定(今のところコード持って来てる)
    Private Sub DataGridView_Left_RowPrePaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles leftDataGridView.RowPrePaint
        If (e.PaintParts And DataGridViewPaintParts.Background) = 0 AndAlso
            (e.PaintParts And DataGridViewPaintParts.ContentForeground) = 0 Then
            Exit Sub
        End If

        '背景
        'しましま模様になる
        Dim backColor As Color
        If (e.PaintParts And DataGridViewPaintParts.SelectionBackground) > 0 AndAlso
            (e.State And DataGridViewElementStates.Selected) > 0 Then
            backColor = Color.FromArgb(235, 235, 235)
        Else
            backColor = Color.White
        End If

        If (e.PaintParts And DataGridViewPaintParts.Background) > 0 Then
            Dim width As Integer
            If IsRunnungOnMono Then
                width = e.RowBounds.Width
            Else
                width = leftDataGridView.Columns.GetColumnsWidth(DataGridViewElementStates.Visible)
            End If

            Using b = New SolidBrush(backColor)
                e.Graphics.FillRectangle(Brushes.AliceBlue, New RectangleF(
                                         e.RowBounds.X, e.RowBounds.Y,
                                         width, e.RowBounds.Height))
            End Using
        End If

    End Sub

    Private Sub DataGridView_Left_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles leftDataGridView.RowPostPaint
        Using _pen = New Pen(Color.LightGray)
            e.Graphics.DrawLine(_pen, e.RowBounds.X, e.RowBounds.Y + e.RowBounds.Height - 1, e.RowBounds.X + e.RowBounds.Width, e.RowBounds.Y + e.RowBounds.Height - 1)
        End Using
    End Sub

#End Region

#Region "追加ボタン、削除ボタン"
    Private Sub Button_Add_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addButton.Click
        Dim CountNum As Integer = 0
        Dim IndexNum As Integer = 1

        Dim Strs As String

        Do
            Strs = Convert.ToString(leftDataGridView("SettingName", CountNum).Value)
            If Strs = "設定" + IndexNum.ToString Then
                CountNum = 0 '名前の重複があったのでもう一度探し直し
                IndexNum += 1 '1足した数字の名前がおｋか調べる
            End If
            CountNum += 1
            If CountNum > leftDataGridView.Rows.Count - 1 Then
                'カウントが0にならない且つ行の数より多い == 一致するものがなかった
                Exit Do
            End If
        Loop
        leftDataGridView.Rows.Add()
        leftDataGridView("SettingName", leftDataGridView.Rows.Count - 1).Value = "設定" + IndexNum.ToString
    End Sub

    Private Sub deleteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deleteButton.Click
        '既定の設定の場合は削除できない
        If Convert.ToString(leftDataGridView("SettingName", leftDataGridView.SelectedRows.Item(0).Index).Value) = "既定の設定" Then
            Exit Sub
        End If
        leftDataGridView.Rows.Remove(leftDataGridView.SelectedRows.Item(0))

        leftDataGridView.Focus()
        deleteButton.Focus()
    End Sub

#End Region

#Region "左側のデータ選択された時の右側への表示"

    Sub rightDatagridViewDataShow()
        Dim rightRowIndex As Integer = 0
        Dim leftColumnIndex As Integer = 2

        Dim Row As Integer = leftDataGridView.SelectedRows.Item(0).Index

        While (rightRowIndex < rightDataGridView.RowCount)
            Try
                rightDataGridView(0, rightRowIndex).Value =
                leftDataGridView(rightDataGridView("通知方法名称", rightRowIndex).Value.ToString, Row).Value
            Catch ex As Exception

            End Try
            rightRowIndex += 1
        End While
    End Sub
#End Region

#Region "セルがクリックされた時の処理"
    Private Sub leftDataGridView_CellEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles leftDataGridView.CellEnter

        '起動時は 0 個なのでエラーがでる -> try - chatch
        Try
            'テキストボックスの内容変更
            settingNameTextBox.Text = leftDataGridView("SettingName", leftDataGridView.SelectedRows.Item(0).Index).Value.ToString
            '名前の重複や完全空白の場合に設定名を戻せるようにしておく・・・設定名の記憶
            SettingNameRemember = settingNameTextBox.Text

            'インデックスを記憶しておく
            DataGridView_Left_IndexRemember = leftDataGridView.SelectedRows.Item(0).Index


            '既定の設定だったら名称変更を禁止する
            If Convert.ToString(leftDataGridView("SettingName", leftDataGridView.SelectedRows.Item(0).Index).Value) = "既定の設定" Then
                settingNameTextBox.ReadOnly = True
            Else
                settingNameTextBox.ReadOnly = False
            End If

            rightDatagridViewDataShow()
        Catch ex As Exception

        End Try

    End Sub

    Sub DataSet()

    End Sub
#End Region

#Region "アラートグループ設定書き換え処理(右側データグリッドビュー編集)"
    Sub rightDataGridView_CellWrite()
        leftDataGridView(rightDataGridView("通知方法名称", DataGridView_Right_IndexRemember).Value.ToString,
                      leftDataGridView.SelectedRows.Item(0).Index).Value = rightDataGridView(0, DataGridView_Right_IndexRemember).Value
    End Sub

    Private Sub rightDataGridView_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles rightDataGridView.CellEndEdit
        rightDataGridView_CellWrite()
    End Sub

    Private Sub rightDataGridView_CellBeginEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles rightDataGridView.CellBeginEdit
        DataGridView_Right_IndexRemember = rightDataGridView.SelectedRows.Item(0).Index
    End Sub

    Private Sub settingNameTextboxChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles settingNameTextBox.TextChanged
        '設定名変更処理
        leftDataGridView("SettingName", leftDataGridView.SelectedRows.Item(0).Index).Value = settingNameTextBox.Text.ToString
    End Sub
#End Region


#Region "設定名称変更(TextBoxからの名前編集)"
    Private Sub settingNameTextBox_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles settingNameTextBox.Validating
        '設定名変更処理
        '空白文字、タブを除去して検査
        Dim str As String = settingNameTextBox.Text
        str = str.Replace(" ", "")
        str = str.Replace("　", "")
        str = str.Replace("\t", "")
        '空白だったら元の名前に戻す
        If str = "" Then
            settingNameTextBox.Text = SettingNameRemember
            'エラー用の記述
            'MsgBox("設定名が不正です。空白のみにしないでください。")
        End If

        leftDataGridView("SettingName", DataGridView_Left_IndexRemember).Value = settingNameTextBox.Text.ToString
    End Sub
#End Region


    Private AlertGroupManager As AlertGroupManager
    Private PluginManager As PluginManager
    Private Settings As Settings

    Public Function GetAlertGroups() As System.Collections.Generic.IList(Of AlertGroup) Implements IAlertGroupClient.GetAlertGroups

    End Function

    Public Function GetSettings() As Settings Implements IAlertGroupClient.GetSettings
        'OutputSettings() を使うと読み込んだ各々のアラート方法についてのオン/オフの情報、
        '設定名、その設定を有効無効が入った型のリストが入手可能
    End Function

    Public Sub Initialize(ByVal alertGroupManager As AlertGroupManager, ByVal pluginManager As PluginManager, ByVal settings As Settings) Implements IAlertGroupClient.Initialize
        Me.AlertGroupManager = alertGroupManager
        Me.PluginManager = pluginManager
        Me.Settings = settings
    End Sub

    Public Shadows Function ShowDialog(ByVal owner As System.Windows.Forms.IWin32Window) As Boolean? Implements IAlertGroupClient.ShowDialog
        If DirectCast(Me, Form).ShowDialog = Windows.Forms.DialogResult.OK Then
            Return True
        Else
            Return False
        End If
    End Function


#Region "データグリッドビュー左右に行と列を追加"
    Sub DataGridViewRegister(ByVal Name As String)
        rightDataGridView.Rows.Add()
        rightDataGridView("通知方法名称", rightDataGridView.RowCount - 1).Value = Name

        Dim column As New DataGridViewCheckBoxColumn
        column.Name = Name
        column.DataPropertyName = Name
        column.HeaderText = Name
        column.ReadOnly = False
        column.Visible = False
        leftDataGridView.Columns.Add(column)
    End Sub
#End Region


    Sub rightDataGridViewInit(ByVal xElemList As List(Of XElement))
        rightDataGridView.Rows.Clear()

        'ここでxElemを元に右側にアイコン追加?

        DataGridViewRegister("Mail")
        DataGridViewRegister("Baloon")
        DataGridViewRegister("Webbrowser")
        DataGridViewRegister("Sound")
    End Sub

    Sub leftDataGridViewInit()
        'ここで設定を左側データグリッドビューの行に追加していく
    End Sub

    'ここで Me.PluginManager->Serializeer->XElement
#Region "PluginManager等の読み込み"
    Sub ReadSettings()
        Dim xElemList = New List(Of XElement)

        For Each plugin In PluginManager.Plugins
            If (plugin.Kind And PluginKinds.Alert) = PluginKinds.Alert Then
                'XElemListに格納
                xElemList.Add((Serializer.Serialize(plugin.Plugin.GetSettings())))
            End If
        Next


        rightDataGridViewInit(xElemList)


    End Sub

#End Region

#Region "並び替えボタン周辺"
    Private Sub CopyDataGridView(ByVal a As Integer, ByVal b As Integer)
        'コピー関数

        'Insertした後に行番号が1つずれるのを修正
        Dim num As Integer = 0
        If a > b Then
            num = 1
        End If

        leftDataGridView.Rows.Insert(b, 1)
        Dim count As Integer = 0
        While (count < leftDataGridView.Columns.Count)
            leftDataGridView(count, b).Value = leftDataGridView(count, a + num).Value
            count += 1
        End While
    End Sub

    Private Sub upButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles upButton.Click
        '一番上は交換不可
        If leftDataGridView.SelectedRows.Item(0).Index < 2 Then
            Exit Sub
        End If

        'CurrentRowsはボタンにフォーカスが移ると値の更新がフォーカスが戻るまで正しく行われない?
        '何度も入れ替えボタンを連打すると変な場所と交換されるので SelectedRowsを使用->こちらは正しく動く


        Dim Index As Integer = leftDataGridView.SelectedRows.Item(0).Index

        CopyDataGridView(Index, Index - 1)
        leftDataGridView.Rows.RemoveAt(Index + 1)
        leftDataGridView.Rows(Index - 1).Selected = True

        'フォーカスを戻してやらないとどうにも値の更新がおかしい
        leftDataGridView.Focus()
        upButton.Focus()
    End Sub

    Private Sub downButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles downButton.Click
        '一番下と一番上は交換不可
        If leftDataGridView.SelectedRows.Item(0).Index = leftDataGridView.RowCount - 1 Or leftDataGridView.SelectedRows.Item(0).Index = 0 Then
            Exit Sub
        End If

        'CurrentRowsはボタンにフォーカスが移ると値の更新がフォーカスが戻るまで正しく行われない?
        '何度も入れ替えボタンを連打すると変な場所と交換されるので SelectedRowsを使用->こちらは正しく動く

        Dim Index As Integer = leftDataGridView.SelectedRows.Item(0).Index

        CopyDataGridView(Index, Index + 2)
        leftDataGridView.Rows.RemoveAt(Index)
        leftDataGridView.Rows(Index + 1).Selected = True

        'フォーカスを戻してやらないとどうにも値の更新がおかしい
        leftDataGridView.Focus()
        downButton.Focus()

    End Sub

#End Region


End Class

